package api

import (
	"encoding/json"
	"fmt"

	"chaincode/model"
	"chaincode/pkg/utils"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

func CheckHouse(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	// 房屋认证
	// 接收:房产证编号 身份证号
	// 回复:true:true 房产证与身份证的匹配结果:是否可以用于出租

	data, err := utils.GetStateByPartialCompositeKeys2(stub, model.HouseManCenterKey, args)

	if err != nil {
		return shim.Error(fmt.Sprintf("%s", err))
	}
	var HouseManCenterList []model.HouseManCenter
	for _, v := range data {
		if v != nil {
			var houseManCenter model.HouseManCenter
			err := json.Unmarshal(v, &houseManCenter)
			if err != nil {
				return shim.Error(fmt.Sprintf("QueryRealEstateList-反序列化出错: %s", err))
			}
			HouseManCenterList = append(HouseManCenterList, houseManCenter)
		}
	}
	if len(HouseManCenterList) == 0 {
		return shim.Error("false")
	}

	return shim.Success([]byte("true"))

}

// 房管局上链智能合约
func AddHouse(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	// 接收数据: 房产证号(key)  身份证号 : 是否可以用于出租(value)

	if len(args) != 2 {
		return shim.Error("Incorrect number of arguments. Expecting 2")
	}

	houseManCenter := &model.HouseManCenter{
		HouseManId: args[0],
		Id:         args[1],
	}

	err := utils.WriteLedger(houseManCenter, stub, model.HouseManCenterKey, []string{houseManCenter.HouseManId, houseManCenter.Id})
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success(nil)
}
